package com.ferryc.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ferryc.commons.entity.TreeNode;
import com.ferryc.commons.service.CommonService;
import com.ferryc.commons.utils.StringUtil;
import com.ferryc.constant.GlobalConstant;
import com.ferryc.modules.sys.entity.SysOrganization;
import com.ferryc.modules.sys.mapper.ISysOrganizationMapper;
import com.ferryc.modules.sys.service.ISysOrganizationService;

/**
 * 
 * 类名: ISysOrganizationService <br/>
 * 作用： 服务<br/>
 * 方法： <br/>
 * 创建者: Ferry C <br/>
 * 添加时间: 2017年12月03日 07:33:41 <br/>
 * 
 */
@Service
@Transactional(readOnly = true)
public class SysOrganizationServiceImpl extends CommonService<SysOrganization> implements ISysOrganizationService {

	@Autowired
	private ISysOrganizationMapper sysOrganizationMapper;

	@Override
	protected void init() {
		super.mapper = sysOrganizationMapper;
	}

	@Override
	public List<TreeNode> selectTreeList(SysOrganization sysOrganization) {

		List<SysOrganization> list = sysOrganizationMapper.getOrgTree();
		return createNode(list, SysOrganization.SYSTEM_PARENT_ID);
	}

	private List<TreeNode> createNode(List<SysOrganization> menuList, String parentId) {
		List<TreeNode> nodeList = new ArrayList<>();
		for (Iterator iterator = menuList.iterator(); iterator.hasNext();) {
			SysOrganization sysOrg = (SysOrganization) iterator.next();
			if (parentId.equals(sysOrg.getParentId())) {
				TreeNode treeNode = new TreeNode();
				treeNode.setId(sysOrg.getId());
				treeNode.setText(sysOrg.getOrgName());
				if (GlobalConstant.YES.equals(sysOrg.getIsParent())) {
					treeNode.setChildren(createNode(menuList, sysOrg.getId()));
				}
				nodeList.add(treeNode);
				treeNode = null;
			}
		}
		return nodeList;
	}

	@Override
	public boolean checkOrgName(SysOrganization sysOrganization) {
		SysOrganization queryOrg = new SysOrganization();
		queryOrg.setOrgName(sysOrganization.getOrgName());
		queryOrg.setParentId(sysOrganization.getParentId());
		queryOrg.setStatus(StringUtil.EMPTY);
		List<SysOrganization> orgList = sysOrganizationMapper.listByEntity(queryOrg);
		if (CollectionUtils.isEmpty(orgList)) {
			return Boolean.TRUE;
		}
		if (StringUtil.isBlank(sysOrganization.getId())) {
			return Boolean.FALSE;
		} else {
			if (orgList.size() == 1 && orgList.get(0).getId().equals(sysOrganization.getId())) {
				return Boolean.TRUE;
			}
			return Boolean.FALSE;
		}
	}

}